import { PlusOutlined, RedoOutlined } from "@ant-design/icons";
import { Table, Tag, Divider, Popconfirm, message, Badge, Button, Modal, DatePicker, Drawer, Progress, notification, Input } from "antd";
import React, { Component, Fragment } from "react";
import { getThemeBydepartmentApi, deleteThemeApi, releaseThemeApi, stopThemeApi, queryRecordByFormKeyApi, getStatisticalAnswerAPi, getReleaseThemeNumApi, queryItemsApi } from "../js/api"
import moment from "moment";
import { exportExcel } from "../js/utils.js";
import "../css/questionform.css"

class QuestionForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            formlist: [],
            tableloading: true,
            open: false,             //发布时间模态框显隐
            confirmLoading: false,   //发布loading
            drawerOpen: false,  //统计界面
            itemsRecord: [],  //表单项统计
            formKey: "",
            startTime: "",
            endTime: ""
        }
    }

    //创建容器用于获取input实例实现链接复制
    input = React.createRef()

    componentDidMount() {
        this.refreshData();
    }
    //获取学校所有表单
    refreshData = () => {
        //设置tableloading: true看似多余实则有用，在刷新列表时显示加载动画
        this.setState({
            tableloading: true
        })
        const schoolId = sessionStorage.getItem("departmentId");
        getThemeBydepartmentApi(schoolId)
            .then(res => {
                this.setState({
                    formlist: res.data.reverse(),
                    tableloading: false
                })
            })
    }
    //删除表单
    deleteTheme = (formKey) => {
        this.setState({ tableloading: true })
        deleteThemeApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    message.success("删除成功");
                    this.refreshData(); //删除后重新获取学校表单，更新列表
                }
                else {
                    message.error("删除失败")
                    this.setState({ tableloading: false })
                }
            })
    }
    //发布表单
    releaseTheme = () => {
        if (this.state.formKey && this.state.startTime && this.state.endTime) {
            this.setState({
                tableloading: true,
                confirmLoading: true
            })
            releaseThemeApi({
                formKey: this.state.formKey,
                startTime: this.state.startTime,
                endTime: this.state.endTime
            }).then(res => {
                if (res.data.msg == "success") {
                    message.success("发布成功");
                    this.setState({
                        confirmLoading: false,
                        formKey: "",
                        open: false,
                    })
                    this.refreshData(); //发布后重新获取学校表单，更新列表
                }
                else {
                    this.setState({
                        confirmLoading: false,
                        tableloading: false
                    })
                    message.error("发布失败")
                }

            })
        }
        else
            message.warning("不可为空")

    }
    //停止发布
    stopTheme = (formKey) => {
        this.setState({ tableloading: true })
        stopThemeApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    message.success("中止成功");
                    this.refreshData(); //停止发布后重新获取学校表单，更新列表
                }
                else {
                    message.error("中止失败")
                    this.setState({ tableloading: false })
                }
            })
    }
    //跳转至表单创建页面
    toCreateForm = () => {
        const schoolId = sessionStorage.getItem("departmentId")
        //window.open("http://localhost:3001/create?schoolId=" + schoolId)
        window.open("http://47.111.158.147:3001/create?schoolId=" + schoolId)
    }

    //统计题目的选项选择比例
    record = (formKey) => {
        getStatisticalAnswerAPi(formKey).then(res => {
            //设置percent属性（选项的选择比例）用于显示
            res.data.forEach((item, index) => {
                if (item.options) {
                    let allnum = 0;
                    //计算题目选项选择数总和，作为除数
                    item.options.forEach(option => {
                        allnum += option.num
                    })
                    //设置percent属性（选项的选择比例）用于显示
                    item.options.forEach((option, i) => {
                        if (allnum == 0)
                            res.data[index].options[i].percent = 0
                        else
                            res.data[index].options[i].percent = (option.num / allnum * 100).toFixed(0)//保留整数
                    })
                }
            })
            this.setState({
                drawerOpen: true,
                itemsRecord: res.data.filter(item => item.options)  //暂时只统计选择 不统计文本
            })
        })
    }
    //关闭统计
    onCloseDrawer = () => {
        this.setState({
            drawerOpen: false
        })
    }

    //以下日期api为限制表单有效期配置
    range = (start, end) => {
        const result = []
        for (let i = start; i < end; i++) {
            result.push(i)
        }
        return result
    }
    // 日期禁用
    disabledDate = (current) => {
        // return current && current < moment().subtract(1, 'days')
        return current && current < moment().subtract(1, 'days').endOf('day')
        // return current && current < moment().endOf('day')
    }
    // 时间禁止
    /* 显示有问题
     disabledTime = (dates) => {
         const hours = moment().hours()// 0~23
         //const minutes = moment().minutes()// 0~59
         //const seconds = moment().seconds()// 0~59
         // 当日只能选择当前时间之后的时间点
         if (moment(dates).date() === moment().date()) {
             return {
                 disabledHours: () => this.range(0, 24).splice(0, hours + 1)
             }
         }
     }
     */
    //发布时间设定框显示
    showModal = (formKey, displayType) => {
        //微信小程序端最多可存在一个已发布表单，判断是否存在已发布表单
        if (displayType == 1)
        {
            getReleaseThemeNumApi(sessionStorage.getItem("departmentId"), displayType).then(res => {
                if (res.data.data == "无法发布") {
                    notification.info({
                        message: "小程序端已有表单正在发布中，请先停止"
                    })
                }
                else
                    this.setState({
                        open: true,
                        formKey
                    });
            })
        }
        else {
            this.setState({
                open: true,
                formKey
            });
        }
    };
    //关闭显示发布时间设定框
    handleCancel = () => {
        this.setState({
            open: false,
            formKey: "",
            confirmLoading: false,
            tableloading: false
        })
    };

    //导出提交记录
    async exportSubmissionRecord(formKey, contentType) {
        // Excel标题
        let header = []
        let outerData = []
        await queryItemsApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    header.push({
                        title: "用户id",
                        dataIndex: "userId",
                        key: "userId"
                    });
                    header.push({
                        title: "用户名",
                        dataIndex: "userName",
                        key: "userName"
                    });
                    header.push({
                        title: "提交时间",
                        dataIndex: "modifyTime",
                        key: "modifyTime"
                    });
                    if (contentType == 2) {
                        header.push({
                            title: "分数",
                            dataIndex: "score",
                            key: "score"
                        });
                    }
                    res.data.data.forEach((item, index) => {
                        header.push({
                            title: item.formItemProps.label,
                            dataIndex: item.formItemProps.name,
                            key: item.formItemProps.name
                        });
                    })

                    if (contentType === 2) {
                        let answer = {}
                        answer["userId"] = "考试答案"
                        answer["userName"] = ""
                        answer["modifyTime"] = ""
                        answer["score"] = ""
                        res.data.data.forEach((item, index) => {
                            //判断这是否是考试题
                            if (item.formItemProps.hasOwnProperty("answer")) {
                                answer[header[index + 4].key] = ""
                                //单选题
                                if (item.type === "radio") {
                                    let max = 0//寻找最佳答案（因为有可能有次优解）
                                    for (let i = 0; i < item.formItemProps.answer.length; i++) {
                                        if (item.formItemProps.answer[i].score > 0 && item.formItemProps.answer[i].score > item.formItemProps.answer[max].score) {
                                            max = i;
                                        }
                                    }
                                    answer[header[index + 4].key] = item.formItemProps.answer[max].value
                                }
                                //多选题
                                else if (item.type === "checkbox") {
                                    for (let i = 0; i < item.formItemProps.answer.length; i++) {
                                        if (item.formItemProps.answer[i].score > 0) {
                                            answer[header[index + 4].key] = answer[header[index + 4].key] + item.formItemProps.answer[i].value + ","
                                        }
                                    }
                                }
                            }
                            else {
                                answer[header[index + 4].key] = ""
                            }
                        });
                        outerData.push(answer);
                    }
                }
            })

        await queryRecordByFormKeyApi(formKey)
            .then(res => {
                if (contentType !== 2) {
                    res.data.forEach((item, index) => {
                        let temp = {}
                        temp["userId"] = item.userId
                        temp["userName"] = item.userName
                        temp["modifyTime"] = item.modifyTime
                        for (let i = 3; i < header.length; i++) {
                            temp[header[i].key] = item.data[i - 3].content;
                        }
                        outerData.push(temp);
                    });
                }
                else if (contentType === 2) {
                    res.data.forEach((item, index) => {
                        let temp = {}
                        temp["userId"] = item.userId
                        temp["userName"] = item.userName
                        temp["modifyTime"] = item.modifyTime
                        temp["score"] = item.score
                        for (let i = 4; i < header.length; i++) {
                            temp[header[i].key] = item.data[i - 4].content;
                        }
                        outerData.push(temp);
                    });
                }
            })
        if (outerData.length == 0) {
            message.warning("目前没有提交数据")
        }
        else {
            exportExcel(header, outerData, "提交记录.xlsx")
        }
    }

    render() {
        //table列配置
        const columns = [
            {
                title: '表单名称',
                dataIndex: 'name',
                key: 'name',
                width: "25%"
            },
            {
                title: '类型',
                dataIndex: 'contentType',
                key: 'contentType',
                width: "13%",
                //筛选配置
                filters: [
                    {
                        text: "问卷",
                        value: 1
                    },
                    {
                        text: "考卷",
                        value: 2
                    },
                    {
                        text: "投票",
                        value: 3
                    }
                ],
                //筛选
                onFilter: (value, record) => record.contentType == value,
                render: (contentType) => {
                    switch (contentType) {
                        case 1:
                            return "问卷"
                        case 2:
                            return "考卷"
                        case 3:
                            return "投票"
                    }
                }
            },
            {
                title: '填写途径',
                dataIndex: 'displayType',
                key: 'displayType',
                width: "15%",
                //筛选配置
                filters: [
                    {
                        text: "小程序",
                        value: 1
                    },
                    {
                        text: "网页",
                        value: 2
                    }
                ],
                //筛选
                onFilter: (value, record) => record.displayType == value,
                render: (displayType) => {
                    switch (displayType) {
                        case 1:
                            return "小程序"
                        case 2:
                            return "网页"
                    }
                }
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                width: "12%",
                //status 0:未发布 1:发布中 2:停止发布
                //筛选配置
                filters: [
                    {
                        text: "未发布",
                        value: 0
                    },
                    {
                        text: "发布中",
                        value: 1
                    },
                    {
                        text: "已停止",
                        value: 2
                    }
                ],
                //筛选
                onFilter: (value, record) => record.status == value,
                render: (status) => {
                    return (
                        <Tag color={
                            (() => {
                                switch (status) {
                                    case 1:
                                        return "#2db7f5"
                                    case 0:
                                        return "blue"
                                    case 2:
                                        return "silver"
                                    default:
                                        return null;
                                }
                            })()}>
                            {
                                (() => {
                                    switch (status) {
                                        case 1:
                                            return "发布中"
                                        case 0:
                                            return "未发布"
                                        case 2:
                                            return "已停止"
                                        default:
                                            return null;
                                    }
                                })()
                            }</Tag>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                width: "35%",
                render: (text, record) => {
                    return (
                        <Fragment>
                            {/* <a href={`http://localhost:3001/detail?schoolId=${record.departmentId}&formkey=${record.formKey}`} target="_blank"> */}
                            <a href={`http://47.111.158.147:3001/detail?schoolId=${record.departmentId}&formkey=${record.formKey}`} target="_blank">
                                查看
                            </a>
                            <Divider type="vertical" />
                            {(() => {
                                switch (record.status) {
                                    case 1:
                                        return (
                                            <Fragment>
                                                <Popconfirm title="您确定要停止此表单的发布吗" onConfirm={() => { this.stopTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>停止发布</a>
                                                </Popconfirm>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.record(record.formKey)} >统计</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.exportSubmissionRecord(record.formKey, record.contentType)} >导出提交记录</a>
                                            </Fragment>
                                        )
                                    case 0:
                                        return (
                                            <Fragment>
                                                <a onClick={() => this.showModal(record.formKey, record.displayType)} >发布</a>
                                                <Divider type="vertical" />
                                                {/* <a href={`http://localhost:3001/update?schoolId=${record.departmentId}&formkey=${record.formKey}`} target="_blank"> */}
                                                <a href={`http://47.111.158.147:3001/update?schoolId=${record.departmentId}&formkey=${record.formKey}`} target="_blank">
                                                    更新
                                                </a>
                                                <Divider type="vertical" />
                                                <Popconfirm title="您确定删除吗" onConfirm={() => { this.deleteTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>删除</a>
                                                </Popconfirm>
                                            </Fragment>)
                                    case 2:
                                        return (
                                            <Fragment>
                                                <a onClick={() => this.showModal(record.formKey, record.displayType)} >重新发布</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.record(record.formKey)} >统计</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.exportSubmissionRecord(record.formKey, record.contentType)} >导出提交记录</a>
                                                <Divider type="vertical" />
                                                <Popconfirm title="您确定删除吗" onConfirm={() => { this.deleteTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>删除</a>
                                                </Popconfirm>
                                            </Fragment>
                                        )
                                    default:
                                        return null;
                                }
                            })()}
                        </Fragment>
                    )
                }
            }
        ];
        return (
            <div>
                {/*发布时间设定框 */}
                <Modal
                    title="发布时间"
                    visible={this.state.open}
                    onOk={this.releaseTheme}
                    confirmLoading={this.state.confirmLoading}
                    onCancel={this.handleCancel}
                    okText={"发布"}
                >
                    <DatePicker.RangePicker
                        placeholder={["开始时间", "结束时间"]}
                        showTime
                        style={{ width: "100%" }}
                        onChange={(date, dateString) => {
                            this.setState({
                                startTime: dateString[0],
                                endTime: dateString[1]
                            })
                        }}
                        disabledTime={this.disabledTime}
                        disabledDate={this.disabledDate} />
                </Modal>
                {/*选项统计 */}
                <Drawer
                    visible={this.state.drawerOpen}
                    closable={false}
                    onClose={this.onCloseDrawer}
                    width="35vw"
                >
                    {this.state.itemsRecord.map((itemRecord, index) =>
                        <ItemRecord
                            itemRecord={itemRecord}
                        >
                        </ItemRecord>
                    )}
                </Drawer>
                <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between" }}>
                    <Button type="primary" size="large" style={{ marginRight: 20 }} onClick={this.toCreateForm}>
                        <PlusOutlined />创建表单
                    </Button>
                    <Button size="large" onClick={this.refreshData}>
                        <RedoOutlined />刷新列表
                    </Button>
                </div>
                <Table
                    dataSource={this.state.formlist}    //数据源
                    columns={columns}   //列配置
                    locale={{ emptyText: '暂无数据' }}
                    loading={this.state.tableloading}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showQuickJumper: true,
                        showSizeChanger: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                    //额外展开行 内嵌子表格
                    expandedRowRender={(record) => {
                        return (
                            <div >
                                <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                    <Badge status="processing" text="表单描述" />
                                    <div style={{ paddingLeft: 15, paddingTop: 5 }}>
                                        {record.description ? record.description : "无"}
                                    </div>
                                </p>
                                {/* 表单填写途径为微信端网页时显示链接 */}
                                {record.displayType == 2 ?
                                    <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                        <Badge status="processing" text="网页链接" />
                                        <div style={{ paddingLeft: 15, paddingTop: 5 }}>
                                            <div style={{ display: "flex" }}>
                                                <Input id="linkAddress" ref={this.input} value={record.linkAddress} readOnly style={{ padding: 0, color: "gray", whiteSpace: "nowrap", textOverflow: "ellipsis", overflow: "hidden", width: "34vw", border: "none", backgroundColor: "#fafafa" }}></Input>
                                                <Button style={{ padding: "4.5px 0" }} size="small" type="link" onClick={() => { this.input.current.select(); document.execCommand('copy'); message.success("复制成功") }}>复制</Button>
                                            </div>
                                        </div>
                                    </p> : null}
                                <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                    <Badge status="processing" text="发布时间" />
                                    <div style={{ paddingLeft: 15, paddingTop: 5, paddingBottom: 5 }}>
                                        {record.status !== 0 ? moment(record.startTime).format('YYYY-MM-DD HH:mm:ss') + " -- " + moment(record.endTime).format('YYYY-MM-DD HH:mm:ss') : " 未发布"}
                                    </div>
                                </p>
                                {/*
                                <div>
                                    <Badge status="processing" text="填写记录" />
                                </div>
                                <QuestionFormInnerTable
                                    formKey={record.formKey}
                                />
                                */}
                            </div>
                        )
                    }
                    }
                    //不加的话table会认错
                    rowKey="formKey"
                />
            </div >
        )
    }
}

//内嵌子表格 展示表单填写记录
class QuestionFormInnerTable extends Component {

    constructor() {
        super()
        this.state = {
            formRecord: []
        }
    }
    componentDidMount() {
        queryRecordByFormKeyApi(this.props.formKey).then(res => {
            this.setState({
                formRecord: res.data
            })
        })
    }
    render() {
        const recordColumns = [
            {
                title: "填写者",
                dataIndex: "userId",
                key: "userId"
            },
            {
                title: "分数",
                dataIndex: "score",
                key: "score"
            },
            {
                title: "时间",
                dataIndex: "modifyTime",
                key: "modifyTime",
                render: (modifyTime) => {
                    return moment(modifyTime).format("yyyy-MM-d hh:mm:ss")
                }
            }
        ]

        return (
            <Table
                dataSource={this.state.formRecord}    //数据源
                columns={recordColumns}   //列配置
                locale={{ emptyText: '暂无填写记录' }}
                pagination={{  //分页
                    defaultPageSize: 10, //默认显示几条一页
                    showTotal: function (total) {  //设置显示一共几条数据
                        return '共 ' + total + ' 条数据';
                    },
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [5, 10, 20, 30]
                }}
            />
        )
    }
}

//表单选项统计组件
class ItemRecord extends Component {
    constructor() {
        super()
    }
    render() {
        const itemRecordColumns = [
            {
                title: "选项",
                dataIndex: "label",
                key: "label",
                width: "12vw",
            },
            {
                title: "小计",
                dataIndex: "num",
                key: "num",
                width: "6vw",
                sorter: (a, b) => a.num - b.num,
            },
            {
                title: "比例",
                dataIndex: "percent",
                key: "percent",
                sorter: (a, b) => a.num - b.num,
                render: (percent) => (
                    <Progress percent={percent}
                        status="active"
                    ></Progress>
                )
            }
        ]
        return (
            <Fragment>
                <div style={{ margin: "12px 0" }}>
                    <Badge status="processing" />
                    <span style={{ color: "gray" }}>题目:</span>
                    <span style={{ color: "#66b1ff", marginRight: "4px" }}>{this.props.itemRecord.label}</span>
                    <span style={{ color: "silver" }}>{this.props.itemRecord.type == "radio" ? "[单选题]" : "[多选题]"}</span>
                </div>
                <Table
                    dataSource={this.props.itemRecord.options}    //数据源
                    columns={itemRecordColumns}   //列配置
                    pagination={{ hideOnSinglePage: true }} //单页不显示页码
                />
                <div style={{ height: "2vh" }}></div>
            </Fragment>
        )
    }
}

export { QuestionForm }